using System;
using System.Linq;

namespace CodingDojo.Domain.KataAlarmClock
{
  public class AlarmsManager : IAlarmsManager
  {
    private const int SnoozeTime = 9;

    private readonly IAlarmRepository _repository;

    public AlarmsManager(IAlarmRepository repository)
    {
      _repository = repository;
    }

    public bool AllAlarmsOff
    {
      get { return _repository.FindAll().Count(e => e.On) == 0; }
    }

    public void TurnOn(int id)
    {
      ToggleAlarm(id, true);
    }

    public void TurnOff(int id)
    {
      ToggleAlarm(id, false);
    }

    private void ToggleAlarm(int id, bool onOff)
    {
      var alarm = _repository.FindById(id);
      alarm.On = onOff;
      alarm.WhenSnooze = alarm.When;
    }

    public Alarm CheckAlarms(TimeSpan when)
    {
      foreach (var alarm in _repository.FindAll().Where(e => e.On))
      {
        if (alarm.When == when || alarm.WhenSnooze == when)
          return alarm;
      }
      return null;
    }

    public void Snooze(int id)
    {
      var alarm = _repository.FindById(id);
      alarm.WhenSnooze = alarm.WhenSnooze + new TimeSpan(0, SnoozeTime, 0);
    }
  }
}
